// 导入并配置环境变量
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const { Pool } = require('pg');
const fs = require('fs');
const path = require('path');
const { spawn } = require('child_process');

// 导入路由模块
const setupUserRoutes = require('./user');
const setupLabelRoutes = require('./label');
const setupVideoRoutes = require('./video');
const setupConfigRoutes = require('./config');
const setupCameraRoutes = require('./camera');
const setupChannelRoutes = require('./channel');
const monitorModule = require('./monitor');

// Directory paths
const VIDEOS_DIR = process.env.VIDEOS_DIR || '/data/videos';
const IMAGES_DIR = process.env.IMAGES_DIR || '/data/images';

// 创建Express应用实例
const app = express();

// CORS配置保持不变
app.use(cors({
  origin: function (origin, callback) {
    if (!origin) return callback(null, true);
    if (process.env.NODE_ENV === 'development') {
      callback(null, true);
    } else {
      callback(null, true);
    }
  },
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'x-user-role']
}));

app.use(express.json());

// 新增静态文件配置
app.use((req, res, next) => {
  delete req.headers.range;
  next();
});

app.use(express.static('public', {
  acceptRanges: false,
  range: false,
  setHeaders: (res) => {
    res.setHeader('Cache-Control', 'no-transform');
    res.setHeader('Accept-Ranges', 'none');
  }
}));

// 只保留一个数据库连接池配置（使用带环境变量的版本）
const pool = new Pool({
  host: process.env.DB_HOST || 'db',
  user: process.env.DB_USER || 'aiprs',
  password: process.env.DB_PASSWORD || 'aiprs',
  database: process.env.DB_NAME || 'aiprs',
  port: process.env.DB_PORT || 5432,
  max: process.env.DB_MAX_CONNECTIONS || 20,
  idleTimeoutMillis: process.env.DB_IDLE_TIMEOUT || 30000,
  connectionTimeoutMillis: process.env.DB_CONNECTION_TIMEOUT || 5000,
  keepAlive: true,
  keepAliveInitialDelayMillis: 10000
});

// 添加连接错误处理
pool.on('error', (err, client) => {
  console.error('数据库连接错误:', err.message, err.stack);
  setTimeout(() => {
    console.log('尝试重新建立数据库连接...');
    pool.connect().then(() => {
      console.log('数据库连接已重新建立');
    }).catch(reconnectErr => {
      console.error('重新连接失败:', reconnectErr.message);
    });
  }, 2000);
});

// 添加健康检查端点
app.get('/api/health', async (req, res) => {
  try {
    const client = await pool.connect();
    await client.query('SELECT NOW()');
    client.release();
    res.status(200).json({ status: 'healthy', timestamp: new Date() });
  } catch (error) {
    console.error('健康检查失败:', error);
    res.status(503).json({ status: 'unhealthy', error: error.message });
  }
});

// Serve thumbnail images
app.get('/api/images/:imageName', (req, res) => {
  const { imageName } = req.params;
  const imagePath = path.join(IMAGES_DIR, imageName);
  
  console.log(`Serving image: ${imagePath}`);

  // Check if image exists
  if (fs.existsSync(imagePath)) {
    res.sendFile(imagePath);
  } else {
    // Fallback to placeholder if image doesn't exist yet
    const placeholderPath = path.join(__dirname, 'placeholder.jpg');
    console.log(`Image not found: ${imageName}, using placeholder: ${placeholderPath}`);
    res.sendFile(placeholderPath);
  }
});

// 使用路由模块
app.use(setupUserRoutes(pool));
app.use(setupLabelRoutes(pool));
app.use(setupVideoRoutes(pool));
app.use(setupConfigRoutes(pool));
app.use(setupCameraRoutes(pool));
app.use(setupChannelRoutes(pool));

// 初始化监控并调用monitorDirectory函数 - 新增这两行
const monitorDirectory = monitorModule(VIDEOS_DIR, IMAGES_DIR);
monitorDirectory();

// 服务器启动
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});
